from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import hotel_passenger as schemas
from app.database.models.erp import HotelOrder, HotelOrderPassenger
from app.database.models.base import User

router = APIRouter()

@router.get("/orders/{hotel_order_id}/passengers", response_model=List[schemas.HotelOrderPassenger])
def list_hotel_passengers(
    hotel_order_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取指定酒店订单的所有乘客信息"""
    try:
        # 检查酒店订单是否存在并验证权限
        order = db.query(HotelOrder).filter(HotelOrder.ID == hotel_order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Hotel order not found")
        
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 获取乘客列表
        passengers = db.query(HotelOrderPassenger).filter(
            HotelOrderPassenger.hotel_order_id == hotel_order_id
        ).all()
        
        return passengers
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error fetching passengers: {str(e)}"
        )

@router.post("/orders/{hotel_order_id}/passengers", response_model=schemas.HotelOrderPassenger)
def create_hotel_passenger(
    *,
    db: Session = Depends(deps.get_db),
    hotel_order_id: int,
    passenger_in: schemas.HotelOrderPassengerCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """为酒店订单添加乘客信息"""
    try:
        # 检查酒店订单是否存在并验证权限
        order = db.query(HotelOrder).filter(HotelOrder.ID == hotel_order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Hotel order not found")
        
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 创建乘客记录
        passenger_data = passenger_in.dict()
        passenger_data["hotel_order_id"] = hotel_order_id
        
        passenger = HotelOrderPassenger(**passenger_data)
        db.add(passenger)
        db.commit()
        db.refresh(passenger)
        return passenger
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/passengers/{passenger_id}", response_model=schemas.HotelOrderPassenger)
def update_hotel_passenger(
    *,
    db: Session = Depends(deps.get_db),
    passenger_id: int,
    passenger_in: schemas.HotelOrderPassengerUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新乘客信息"""
    try:
        # 获取乘客记录
        passenger = db.query(HotelOrderPassenger).filter(
            HotelOrderPassenger.ID == passenger_id
        ).first()
        if not passenger:
            raise HTTPException(status_code=404, detail="Passenger not found")

        # 检查权限
        order = db.query(HotelOrder).filter(
            HotelOrder.ID == passenger.hotel_order_id
        ).first()
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新乘客信息
        update_data = passenger_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(passenger, field, value)

        db.add(passenger)
        db.commit()
        db.refresh(passenger)
        return passenger
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/passengers/{passenger_id}")
def delete_hotel_passenger(
    *,
    db: Session = Depends(deps.get_db),
    passenger_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除乘客信息"""
    try:
        # 获取乘客记录
        passenger = db.query(HotelOrderPassenger).filter(
            HotelOrderPassenger.ID == passenger_id
        ).first()
        if not passenger:
            raise HTTPException(status_code=404, detail="Passenger not found")

        # 检查权限
        order = db.query(HotelOrder).filter(
            HotelOrder.ID == passenger.hotel_order_id
        ).first()
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 删除乘客记录
        db.delete(passenger)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 